<template>
  <a-modal title="完成取车" :visible="visible" width="85vw" unmount-on-close @cancel="close">
    <div class="page-container relative give-car-wrapper" style="position: relative">
      <div class="page-form-block">
        <!-- 统计 -->
        <summary-info :summaryList="summaryLease" />
        <a-divider />
        <summary-info :summaryList="summaryCarInfo" />
      </div>
      <a-divider />

      <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
        <card title="还车信息" style="margin-top: 20px">
          <box-info :carId="form.carId" style="margin-bottom: 20px" />
          <page-form-row>
            <page-form-item label="还车里程" field="endCarMileage">
              <i-input-number
                :precision="0"
                :min="prevGivecarMileage ? prevGivecarMileage : undefined"
                unit="公里"
                v-model="form.endCarMileage"
                @change="endCarMileChangeFn"
              />
            </page-form-item>
            <page-form-item label="还车油(电)量" field="endCarOil">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.endCarOil" />
            </page-form-item>
            <page-form-item field="returnStaffId" label="还车人">
              {{ form.returnStaffName }}
            </page-form-item>
            <page-form-item field="useEndTime" label="还车时间">
              <i-date-picker
                :allow-clear="false"
                class="w-full"
                v-model="form.useEndTime"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:00"
                :disabled-date="disabledDate"
                :disabled-time="disabledTime"
                :time-picker-props="{
                  format: 'HH:mm',
                  defaultValue: '00:00',
                }"
                showTime
                @change="useEndTimeChangeFn"
                popup-container=".give-car-wrapper"
              />
            </page-form-item>
            <page-form-item label="还车备注" size="2/3">
              <i-textarea v-model="form.useEndRemark" />
            </page-form-item>
            <page-form-item label="还车照片" size="1">
              <upload-img v-model="form.fileIds" />
            </page-form-item>
            <page-form-item label="还车视频" size="1" class="mb-0">
              <upload-video v-model="form.videoFileIds" :max="1" />
            </page-form-item>
          </page-form-row>
        </card>
        <!-- 费用信息 -->
        <div class="relative fee-pane-content">
          <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
            <card toggle :showDivider="false">
              <template #title>还车费用</template>
              <template v-for="(item, index) in feeForm.orderFee" :key="index">
                <fee-pane :orderFeeIndex="index" :disabledOnlineFee="orderInfo.orderSource == 1">
                  <template #returnDepositFee="{ feeOption, showDivider }">
                    <card :title="feeOption.feeName" :showDivider="showDivider">
                      <return-deposit :orderId="orderInfo.id" />
                    </card>
                  </template>
                </fee-pane>
              </template>
            </card>
          </page-form>
        </div>
      </page-form>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
    </template>
  </a-modal>
  <!-- 查询当前订单的还车车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>
<script setup name="ShortOrderReturnCar">
  import { ref, provide, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { getShortOrdrDetails } from '@/api/order/sOrder'
  import { getLongOrderDetails } from '@/api/order/czsOrder'
  import { checkExistEtcOrderApi } from '@/api/order/etcOrder'
  import finishEtcOrderModal from '@/views/order/etc-order/components/finish-etc-order-modal.vue'
  import { finishReturnCar, shortOrdrCalcPrice, longOrderCalcPrice } from '@/api/business/workorder'
  import feePane from '../giveCar/order-fee/fee-pane.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from '../giveCar/order-fee/fee-utils.js'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import useNavigate from '@/hooks/useNavigate'
  import summaryInfo from '../giveCar/summary-info.vue'
  import boxInfo from '../../../components/box-modal.vue'
  import returnDeposit from './return-deposit.vue'
  import { handleContracList } from '@/views/order/long-order//utils'
  import { Message, Notification } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'
  const { navigateBack } = useNavigate()
  const emit = defineEmits(['ok'])
  const userStore = useUserStore()
  const route = useRoute()
  const router = useRouter()
  const orderId = ref(null)
  const orderInfo = ref({})
  const memberInfo = ref({})
  const visible = ref(false)
  const orderType = ref(null) //1短 2长

  const form = ref({
    id: orderId.value,
    useEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    depositDeductFlag: 0,
    changeDepositFlag: 0,
  })
  const initForm = () => {
    form.value = {
      id: orderId.value,
      useEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      depositDeductFlag: 0,
      changeDepositFlag: 0,
    }
  }
  // 处理默认值
  const rules = {
    returnStaffId: [{ required: true, message: '请选择还车人' }],
    useEndTime: [{ required: true, message: '请选择还车时间' }],
    endCarMileage: [{ required: true, message: '请输入还车里程' }], // 还车里程
    endCarOil: [{ required: true, message: '请输入还车油(电)量' }], // 还车油(电)量
  }
  const formRef = ref()
  provide('form', form)

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.startTime ? `${orderInfoVal.startTime} - ${orderInfoVal.endTime}` : '-',
        },
        { label: '租期', value: orderInfoVal.rentDays },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '车型', value: orderInfoVal.originalSiteModelName },
        { label: '交车车型', value: orderInfoVal.carModelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.carLicenseNo }],
    ]
  })

  const summaryCarInfo = computed(() => {
    const orderCarInfos = orderInfo.value.shortOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return [
      [
        {
          label: '交车里程',
          value: lastOrderCarInfo.startCarMileage ? lastOrderCarInfo.startCarMileage + ' 公里' : '',
        },
        { label: '交车油(电)量', value: lastOrderCarInfo.startCarOil ? lastOrderCarInfo.startCarOil : '' },
      ],
    ]
  })

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee', 'returnRefuseFee', 'returnDepositFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const prevGivecarMileage = computed(() => {
    if (orderType.value == 1) {
      let shortOrderCarInfoDtos = orderInfo.value.shortOrderCarInfoDtos
      if (shortOrderCarInfoDtos && shortOrderCarInfoDtos.length) {
        return shortOrderCarInfoDtos[shortOrderCarInfoDtos.length - 1].startCarMileage
      }
      return null
    } else {
      let longOrderCarInfoDtos = orderInfo.value.longOrderCarInfoDtos
      if (longOrderCarInfoDtos && longOrderCarInfoDtos.length) {
        return longOrderCarInfoDtos[longOrderCarInfoDtos.length - 1].startCarMileage
      }
      return null
    }
  })
  const prevGivecarTime = computed(() => {
    if (orderType.value == 1) {
      let shortOrderCarInfoDtos = orderInfo.value.shortOrderCarInfoDtos
      if (shortOrderCarInfoDtos && shortOrderCarInfoDtos.length) {
        return shortOrderCarInfoDtos[shortOrderCarInfoDtos.length - 1].useStartTime
      }
      return null
    } else {
      let longOrderCarInfoDtos = orderInfo.value.longOrderCarInfoDtos
      if (longOrderCarInfoDtos && longOrderCarInfoDtos.length) {
        return longOrderCarInfoDtos[longOrderCarInfoDtos.length - 1].useStartTime
      }
      return null
    }
  })

  // disabled Date|Time
  const disabledDate = (dateVal) => {
    const prevDate = prevGivecarTime.value
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledTime = (current) => {
    let options = {}
    const prevDate = prevGivecarTime.value
    if (prevDate) {
      let currentTime = current ? dayjs(current) : dayjs()
      let currentTime_year = currentTime.year()
      let currentTime_month = currentTime.month()
      let currentTime_date = currentTime.date()
      let currentTime_hour = currentTime.hour()
      let prevDateTime = dayjs(prevDate)
      let prevDateTime_year = prevDateTime.year()
      let prevDateTime_month = prevDateTime.month()
      let prevDateTime_date = prevDateTime.date()
      let prevDateTime_hour = prevDateTime.hour()
      let prevDateTime_minute = prevDateTime.minute()
      if (prevDateTime_minute == 59) {
        options.disabledHours = () => range(0, prevDateTime_hour + 1)
        options.disabledMinutes = () => []
      } else {
        options.disabledHours = () => range(0, prevDateTime_hour)
        options.disabledMinutes = () => range(0, prevDateTime_minute + 1)
      }
      // 用户选择的是 未来 的天
      if (currentTime_year > prevDateTime_year || currentTime_month > prevDateTime_month || currentTime_date > prevDateTime_date) {
        options = {}
      } else {
        // 用户选择的是 未来 的小时
        if (currentTime_hour > prevDateTime_hour) {
          options.disabledMinutes = () => {
            return []
          }
        }
      }
    }
    return options
  }
  // 默认员工
  const defaultStaffId = ref()

  // 还车里程变更
  const endCarMileChangeFn = () => {
    calcDefaultFee('endCarMile')
  }
  // 还车时间变更
  const useEndTimeChangeFn = () => {
    calcDefaultFee('useEndTime')
  }
  // 计算默认费用
  const calcDefaultFee = (type) => {
    const param = {
      endTime: form.value.useEndTime,
      endCarMileage: form.value.endCarMileage,
      id: orderId.value,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      type: 2,
    }
    shortOrdrCalcPrice(param).then((res) => {
      const result = res.result
      const otherPrice = result.otherPrice
      if (otherPrice) {
        let feeDetailList = feeForm.value.orderFee[0].feeDetailList
        feeDetailList.forEach((feeCategory) => {
          if (feeCategory.type == 'extraFee') {
            let childrenList = feeCategory.childrenList
            childrenList.forEach((feeItem) => {
              if (feeItem.itemName == '超里程费') {
                if (type == 'endCarMile') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超里程费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
              if (feeItem.itemName == '超时费') {
                if (type == 'useEndTime') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超时费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
            })
          }
        })
      }
    })
  }

  const okLoading = ref(false)
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    okLoading.value = true
    finishReturnCar(param)
      .then((res) => {
        console.log(res)
        Message.success(res.message)
        close()
        emit('ok')
      })
      .finally(() => (okLoading.value = false))
  }
  // 检验还车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        let params = {
          refType: 1,
          refId: orderId.value,
          carId: orderInfo.value.carId,
          endTime: form.value.useEndTime,
        }
        checkExistEtcOrderApi(params).then((res) => {
          let result = res.result
          if (result.existOrder) {
            let params = {
              carLicenseNo: orderInfo.value.carLicenseNo,
              operateStr: '还车',
            }
            etcModalRef.value.open(params)
          } else {
            submitOperateFn()
          }
        })
      }
    })
  }

  const open = (record) => {
    // 重置form
    initForm()
    visible.value = true
    form.value.returnStaffId = record.workOperatorId //工单负责人id
    form.value.returnStaffName = record.workOperatorName
    form.value.id = record.id
    form.value.carId = record.carId
    orderId.value = record.refId

    orderType.value = 1
    getShortOrdrDetails({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      // 处理默认值
      // 车务专员 | 当前登录者 id
      defaultStaffId.value = orderInfo.value.returnStaffId || userStore.employeeId
      // 默认还车人
      form.value.returnStaffId = defaultStaffId.value
      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
        // 初始化费用
        initFeeDetail(feeForm.value, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 初始化 超里程费和超时费
        calcDefaultFee('useEndTime')
      })
    })
  }
  // 关闭
  const close = () => {
    form.value = {}
    feeForm.value = {
      randomKey: 0,
      orderFee: [
        {
          // 费用类型（线上费用|线下费用）
          feeType: 1,
          feeDetailList: [],
          priceTemplateId: priceTemplateId,
          feeDetailTypeList: ['extraFee', 'returnRefuseFee', 'returnDepositFee'],
        },
      ],
    }
    visible.value = false
  }
  // 保存
  const handleBeforeOk = () => {
    close()
    emit('ok')
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  .page-container {
    max-height: calc(100vh - 210px);
  }
</style>
